package com.chimm.redpacket.demo_redis.controller;

import com.chimm.redpacket.bean.RedPacket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * 抢红包设计方式二
 *
 * @author Chimm Huang
 */
@RestController
@RequestMapping("/demo02")
public class Demo02Controller {

    private static final Logger logger = LoggerFactory.getLogger(Demo02Controller.class);

    @Autowired
    private RedissonClient redissonClient;

    private static final String RED_PACKET_KEY = "red_packet_demo02";

    @RequestMapping("/add")
    public String addRedPacket(BigDecimal money, Integer num) {
        // 让开，我要发红包啦
        RedPacket redPacket = new RedPacket(money, num);
        logger.info("================ 红包来啦，金额：{} 元，数量：{} 个 ================", money, num);
        List<BigDecimal> splitRedPacket = redPacket.splitRedPacket();

        // 生成红包id
        String id = UUID.randomUUID().toString().replace("-", "");
        redissonClient.getQueue(RED_PACKET_KEY + ":" + id).addAll(splitRedPacket);

        return "红包已发送，id为：" + id;
    }

    @RequestMapping("/get")
    public String getRedPacket(String id, String userId) {
        BigDecimal money = (BigDecimal)redissonClient.getQueue(RED_PACKET_KEY + ":" + id).poll();
        if (money == null) {
            return "手慢了";
        }
        logger.info("================ 用户：{} 抢到了：{} 元 ================", userId, money);
        return "抢到红包，金额为：" + money;
    }
}
